using Avalonia.BiliBili.Views.ChildViews.Search;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Bilibili.Common;
using Bilibili.Model.Common;
using Bilibili.Model.Search;
using DynamicData;
using PCLUntils.Json;
using PCLUntils.Objects;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Avalonia.BiliBili.Views.ChildViews
{
    public partial class SearchVideo : ChildView
    {
        private int PageNum { get; set; } = 1;
        private ObservableCollection<SearchVideoItem> Items { get; }
        public SearchVideo()
        {
            InitializeComponent();
            Items = [];
        }
        public override void AfterInitializeComponent()
        {
            videoList.ItemsSource = Items;
            videoList.ItemClick += Videos_ItemClick;
        }
        private void Videos_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.IsLeftClick && e.ClickItem is ListViewItem item && item.Content is SearchVideoItem videoItem)
                    App.Mapper.NavigateToPlayer(videoItem.aid, PlayMode.Video);
            }
            catch { }
        }
        public override void Callback(object data)
        {
            RunOnUiThread(async () =>
            {
                if (data is InvokeData<string> info)
                {
                    if (info.Clear)
                        Items.Clear();
                    string area = GetTag(areaSelect), type = GetTag(typeSelect);
                    var areaCondition = area.IsEmpty() ? string.Empty : "&tids=" + area;
                    var typeCondition = type.IsEmpty() ? string.Empty : "&order=" + type;
                    var result = await Base.Client.GetVideos(info.Data, PageNum, areaCondition, typeCondition);
                    if (result.IsSuccess())
                    {
                        var model = result.Data;
                        if (model.IsNotEmpty())
                        {
                            if (model.code == 0)
                            {
                                var array = model.result.ParseObject<List<SearchVideoItem>>();
                                if (PageNum == 1)
                                    Items.Clear();
                                Items.AddRange(array);
                            }
                        }
                    }
                    else
                        PopupToast.Show(result?.Message);
                }
            });
        }
    }
}